package com.ntu.rent.web.interceptors;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.ntu.rent.common.base.Constants;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

/**
 * 
 * 公司名称:上海天缘迪科<br/>
 * 工程名称:Rent<br/>
 * 包名:com.ntu.rent.web.interceptors<br/>
 * 文件名:CompetenceInterceptor.java<br/>
 * 功能描述:
 * 完成权限控制
 *<br/>
 * 创建时间:2014-2-19 下午01:52:15<br/>
 * @author zeegates
 *
 */
public class CompetenceInterceptor implements Interceptor {

	/**
	 * 
	 */
	private static final long serialVersionUID = -2513864903793049028L;

	@Override
	public void destroy() {

	}

	@Override
	public void init() {

	}

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		
		HttpServletRequest request = ServletActionContext.getRequest();
		
		HttpServletResponse response = ServletActionContext.getResponse();
		
		HttpSession session = request.getSession();
		
		String accessableActions = 
			(String)session.getAttribute(Constants.ACCESSABLE_ACTIONS);
		/*
		 * 获取请求的资源
		 */
		String resourcesRequired = request.getRequestURI().substring(
				request.getRequestURI().lastIndexOf("/"), request.getRequestURI().length());
		invocation.getAction();
		
		if(resourcesRequired.endsWith(".action") || ! resourcesRequired.contains(".")) {
			//请求的是action资源
			
			if(accessableActions == null || !accessableActions.contains(resourcesRequired)) {
				//返回权限不足的
				ServletOutputStream out = response.getOutputStream();
				out.println("<html>");
				out.println("<head>");
				out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
				out.println("</head>");
				out.println("<script>");
				out.println("alert('您没有访问"+resourcesRequired+"的权限');");
				out.println("</script>");
				out.println("</html>");
				out.flush();
				return null;
			}
		}
		return invocation.invoke();
	}

}
